/**
 * Created with IntelliJ IDEA.
 * User: gg
 * Date: 14-4-24
 * Time: 下午4:37
 * To change this template use File | Settings | File Templates.
 */
/**
 * Created with IntelliJ IDEA.
 * User: KSentropy
 * Date: 14-2-18
 * Time: 下午1:41
 * To change this template use File | Settings | File Templates.
 */

$.extend({
    checkUndefined: function (params) {
        if (params == undefined) {
            return true;
        }
        return false;
    },
    dealDefault: function (oldParams, newParams) {
        if ($.checkUndefined(oldParams)) {
            return newParams;
        }
        return oldParams;
    },
    simpleAjax: function (params) {
        $.dealDefault(params, {});
        $.ajax({
            url: $.dealDefault(params.url, ''),
            data: $.dealDefault(params.data, {}),
            type: "POST",
            dataType: "json",
            async: true,
            beforeSend:function(XMLHttpRequest ){
                XMLHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            },
            success: function (data) {
                if (data.success) {
                    if ($.checkUndefined(params.callback)) {
                    } else {
                        params.callback(data);
                    }
                } else {
                    alert(data.message);
                }
            }
        })
    },
    simpleAjaxOrig: function (formObj, url, params) {
        $.dealDefault(params, {});
        $.ajax({
            url: url,
            data: formObj.serialize(),
            type: "POST",
            dataType: "json",
            async: true,
            beforeSend:function(XMLHttpRequest ){
                XMLHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            },
            success: function (data) {
                if (data.success) {
                    if (!$.checkUndefined(params.tableId)) {
                        $('#' + params.tableId).refreshGrid();
                    }
                    if (!$.checkUndefined(params.treeId)) {
                        $('#' + params.treeId).tree('reload');
                    }
                    if ($.checkUndefined(params.success)) {
                        $.alertBox('Info', data.message, 'info');
                    } else {
                        params.success(data.message);
                    }
                    if (!$.checkUndefined(params.onClose)) {
                        params.onClose(data.message);
                    } else {
                        formObj.parents('.parentWindow').closeWindow();
                    }
                } else {
                    $.alertBox('Info', data.message, 'info');
                    formObj.find('.save_button').removeAttr('disabled');
                }
            }
        })
    },
    initAlert: function (params) {
        if ($.checkUndefined(params)) {
            params = {};
        }
        var message = $.dealDefault(params.message, '请选择一条记录');
        var title = $.dealDefault(params.title, '系统提示');
        bootbox.dialog({
            message: message,
            title: title,
            buttons: {
                main: {
                    label: "确定",
                    className: "btn-primary",
                    callback: function () {
                        if (!$.checkUndefined(params.callback)) {
                            params.callback();
                        }
                    }
                }
            }
        });
    },
    initConfirm: function (message, callback) {
        var message = $.dealDefault(message, '你确定要继续吗');
        bootbox.dialog({
            message: message,
            title: '系统提示',
            buttons: {
                main: {
                    label: "取消",
                    className: "btn-default",
                    callback: function () {
                        callback(false);
                    }
                },
                success: {
                    label: "确定",
                    className: "btn-primary",
                    callback: function () {
                        callback(true);
                    }
                }
            }
        });
    },
    openWindow: function (url, windowId, title, width, height) {
        var obj = {};
        if ($("#" + windowId).length > 0) {
            obj = $("#" + windowId);
        } else {
            obj = $('<div class="parentWindow" id="' + windowId + '"></div>');
        }
//        var iframe ='<iframe width=\"100%\" scrolling=\"auto\" height=\"99%\" frameborder=\"false\" allowtransparency=\"true\" style=\"border: medium none;\" src="'+url+'" name=\"main\"></iframe>';
        obj.window({
            title: title,
            width: width,
            height: height,
            modal: true,
            collapsible: false,
            minimizable: false,
            maximizable: false,
//            content: iframe,
            href: url,
            onClose: function () {
                $(this).window('destroy');
            }
        });
        obj.window('center');
    },
    alertBox: function (title, message, type) {
        parent.$.messager.alert(title, message, type);
    },
    confirmBox: function (title, message, callback) {
        parent.$.messager.confirm(title, message, function (r) {
            callback(r);
        });
    }
})
$.fn.extend({
    serializeObject: function () {
        var obj = new Object();
        $.each($(this).serializeArray(), function (index, param) {
            if (!(param.name in obj)) {
                obj[param.name] = param.value;
            }
        });
        return obj;
    },
    refreshGrid: function () {
        $(this).datagrid('reload');
    },
    reloadGrid: function (data) {
        $(this).datagrid('load', data);
    },
    getTableSelectedIds: function () {
        var array = new Array();
        $(this).find('input:checkbox[name=id]:checked').each(function () {
            array.push($(this).val());
        });
        return array;
    },
    initPage: function (params) {
        if ($.checkUndefined(params)) {
            params = {};
        }
        $(this).load(params.url, function () {
            if (!$.checkUndefined(params.callback)) {
                params.callback();
            }
        })
    },
    initTree: function (params) {
        var obj = $(this);
        obj.tree({
            onlyLeafCheck: $.dealDefault(params.onlyLeafCheck, false),
            url: obj.attr('url'),
            animate: true,
            onLoadSuccess: function (node, data) {
                var node1 = obj.tree('find', '0');
                obj.tree('select', node1.target);
            },
            onContextMenu: function (e,node) {
                e.preventDefault();
                if (!$.checkUndefined(params.onContextMenu)) {
                    params.onContextMenu(e,node);
                }

            },
            onClick: function (node) {
                if (!$.checkUndefined(params.onClick)) {
                    params.onClick(node);
                }
            }
        });
    },
    getSelectNodeId: function () {
        var obj = $(this);
        var node = obj.tree('getSelected');
        if (node == null) {
            return null;
        }
        return node.id;
    },
    getSelectNode: function () {
        var obj = $(this);
        var node = obj.tree('getSelected');
        if (node == null) {
            return null;
        }
        return node;
    },
    doDeleteNode: function (params) {
        $.dealDefault(params, {});
        var obj = $(this);
        var node = obj.tree('getSelected');
        var parentNode = obj.tree('getParent', node.target);
        var msg1 = $.dealDefault("要删除的节点是父节点，如果删除将连同子节点一起删掉。\n\n请确认！", params.msg1);
        var msg2 = $.dealDefault("如果删除将连同相关信息一起删掉。\n\n请确认！", params.msg2);
        var msg = '顶层节点不允许删除！';
        if (parentNode == null) {
            $.alertBox('系统提示', msg, 'info');
        } else {
            var isLeaf = obj.tree('isLeaf', node.target);
            if (!isLeaf) {
                msg = msg1;
            } else {
                msg = msg2;
            }
        }
        var nodeId = node.id;
        if (!$.checkUndefined(params.suffix)) {
            nodeId = $.replaceStr(nodeId, params.suffix, '');
        }
        $.confirmBox('确认', msg, function (r) {
            if (r) {
                if ($.checkUndefined(params.success)) {
                    function success(data) {
                        $.alertBox('系统提示', data, 'info');
                        obj.tree('reload');
                        if (!$.checkUndefined(params.tableId)) {
                            $('#' + params.tableId).refreshGrid();
                        }
                    };
                    $.commonAjax(params.url, {ids: nodeId}, {success: success});
                } else {
                    $.commonAjax(params.url, {ids: nodeId}, {success: params.success(data)});
                }
            }
        })
    },
    initPage:function(params){
        var obj = $(this);
        obj.load(params.url, function () {
            if (!$.checkUndefined(params.callback)) {
                params.callback();
            }
        })
    },
    closeWindow: function () {
        $(this).window('close');
    },
    reset: function () {
        $(this).find('input[type!=hidden]').val(null);
    }

});

var allPage = 0;
var currentPage = 0;
var next = 0;
var pre = 0;
var first = 0;
var last = 0;
function initPageParams() {
    allPage = parseInt($('#allPage').val());
    currentPage = parseInt($('#currentPage').attr('page'));
    next = currentPage + 1;
    pre = currentPage - 1;
    first = 1;
    last = allPage;
    var prePage = $('.pagination').first().find('.prePage').first();
    var nextPage = $('.pagination').first().find('.nextPage').first();
    var firstPage = $('.pagination').first().find('.firstPage').first();
    var lastPage = $('.pagination').first().find('.lastPage').first();
    if (currentPage == '1' && currentPage != allPage) {
        pre = currentPage;
    } else if (currentPage == '1' && currentPage == allPage) {
        pre = currentPage;
        next = currentPage;
    } else if (currentPage == allPage) {
        next = currentPage;
    }
}

function disablePageFlag() {
    allPage = parseInt($('#allPage').val());
    currentPage = parseInt($('#currentPage').attr('page'));
    next = currentPage + 1;
    pre = currentPage - 1;
    first = 1;
    last = allPage;
    var prePage = $('.pagination').first().find('.prePage').first();
    var nextPage = $('.pagination').first().find('.nextPage').first();
    var firstPage = $('.pagination').first().find('.firstPage').first();
    var lastPage = $('.pagination').first().find('.lastPage').first();
    if (currentPage == '1' && currentPage != allPage) {
        prePage.parents('li').addClass('disabled');
        firstPage.parents('li').addClass('disabled');
    } else if (currentPage == '1' && currentPage == allPage) {
        prePage.parents('li').addClass('disabled');
        firstPage.parents('li').addClass('disabled');
        lastPage.parents('li').addClass('disabled');
        nextPage.parents('li').addClass('disabled');
    } else if (currentPage == allPage) {
        lastPage.parents('li').addClass('disabled');
        nextPage.parents('li').addClass('disabled');
    }
}
$(function () {
    disablePageFlag();
})
$('body').on('click', '.firstPage', function (e) {
    e.stopPropagation();
    var tableObj = $(this).parents('.row').find('table').first();
    var url = tableObj.attr('url');
    var tableId = tableObj.attr('tableId');
    initPageParams();
    var disabled = $(this).parents('li').attr('class').indexOf('disabled');
    if (disabled >= 0) {
        return false;
    }
    window.location.href = url + '?page=' + first + '&rows=' + 10;
    return false;
})

$('body').on('click', '.prePage', function (e) {
    e.stopPropagation();
    var tableObj = $(this).parents('.row').find('table').first();
    var url = tableObj.attr('url');
    var tableId = tableObj.attr('tableId');
    initPageParams();
    var disabled = $(this).parents('li').attr('class').indexOf('disabled');
    if (disabled >= 0) {
        return false;
    }
    window.location.href = url + '?page=' + pre + '&rows=' + 10;
    return false;
})

$('body').on('click', '.nextPage', function (e) {
    e.stopPropagation();
    var tableObj = $(this).parents('.row').find('table').first();
    var url = tableObj.attr('url');
    var tableId = tableObj.attr('tableId');
    initPageParams();
    var disabled = $(this).parents('li').attr('class').indexOf('disabled');
    if (disabled >= 0) {
        return false;
    }
    window.location.href = url + '?page=' + next + '&rows=' + 10;
    return false;
})

$('body').on('click', '.lastPage', function (e) {
    e.stopPropagation();
    var tableObj = $(this).parents('.row').find('table').first();
    var url = tableObj.attr('url');
    var tableId = tableObj.attr('tableId');
    initPageParams();
    var disabled = $(this).parents('li').attr('class').indexOf('disabled');
    if (disabled >= 0) {
        return false;
    }
    window.location.href = url + '?page=' + last + '&rows=' + 10;
    return false;
})
